import { _decorator, Component, Node, Label, director} from 'cc';
const { ccclass, property } = _decorator;


import { GameConfig } from './config/GameConfig';
import { Game } from './Game';
import { UserModel } from './models/user';
import { TaKuSDK, PlacementType } from './TaKuSDK';
import { ENV } from './config/main';
import { Profile } from './Profile';
import { UserApi } from './api/user';
import { Toast } from './utils/Toast';
import { GlobalEvent } from './events/GlobalEvent';
import { EventTypes } from './events/EventTypes';
import DeviceIdManager from './utils/DeviceIdManager';
import AdCustomRuleBuilder from './utils/AdCustomRuleBuilder';

@ccclass('GameRoot')
export class GameRoot extends Component {
    private USER_ID = "interest_game";
    private USER_DATA = {"interest":"game"}

    private appid: string = "a682d675cd0849";

    @property(Toast)
    toast: Toast = null;

    @property(Label)
    private  deviceInfoLabel: Label = null;

    // 复制设备结果按钮
    @property(Node)
    private copyDeviceInfoBtn: Node = null;

    @property(Node)
    private userBtn: Node = null;
    start() {

        const isEmulator = this.checkEmulator();
        if(isEmulator) return;

        this.initGame();

        const node = director.getScene().getChildByPath("Canvas/game_root/ad_native");
        console.log("native - node", node);

        UserApi.getAppDetail(this.appid).then((res) => {
            // 更新env
            ENV.AD_OPEN = res.isOpenAd === 1;
            ENV.REWARD_VIDEO_OPEN = res.isOpenReward === 1;
            ENV.INTERSTITIAL_OPEN = res.isOpenInter === 1;
            ENV.BANNER_OPEN = res.isOpenBanner === 1;
            ENV.NATIVE_OPEN = res.isOpenNative === 1;

            ENV.MAX_AD_COUNT = res.maxAdCount ? res.maxAdCount : ENV.MAX_AD_COUNT;

           
        }).catch((error) => {
            console.error('获取应用详情失败:', error);
        });

        if(ENV.IS_PASS_LOGIN){
            // 游客登录
            const deviceId = DeviceIdManager.getDeviceId();
            UserApi.guestLogin(deviceId).then((data) => {
                console.log("guestLogin", data);
                UserModel.getInstance().setUserInfo(data);
                this.loadUserAdInfo();

                if(ENV.AD_OPEN){
                    try{
                        const userInfo = UserModel.getInstance().getUserInfo();
                        if(userInfo){
                            const userData = new AdCustomRuleBuilder()
                                .setUserId(userInfo.userInfo.id.toString())
                                .setIsNewUser(true)
                                .setInterest('game')
                                .setLoginDays(userInfo.userInfo.c_login_days)
                                .setLoginTotalDays(userInfo.userInfo.login_total_days)
                                .setAdScene('home')
                                .setIsNewUser(userInfo.isNewUser)
                                .build();
                            console.log("init userData", userData);
                            TaKuSDK.getInstance().init(userInfo.userInfo.username, JSON.stringify(userData));
                        }else{
                            TaKuSDK.getInstance().init(userInfo.userInfo.id.toString(), JSON.stringify(this.USER_DATA));
                        }
                    }catch(e){
                        const user_id = this.USER_ID + Math.random().toString(36).substring(2, 15);
                        console.log("init userData error", e.message);
                        TaKuSDK.getInstance().init(user_id, JSON.stringify(this.USER_DATA));
                    }
                }
            }).catch((error) => {
                console.error('游客登录失败:', error);
            });

             
        }


        GlobalEvent.on(EventTypes.MAX_AD_COUNT_REACHED, this.showToast, this);
       
    }

    checkEmulator(){
        this.copyDeviceInfoBtn.on(Node.EventType.TOUCH_START, this.copyDeviceInfo, this);
        const res = DeviceIdManager.isEmulator();
        this.deviceInfoLabel.string = JSON.stringify(res);
        const resJson = JSON.parse(res);
        console.log("resJson", resJson);
        // 判断是否是模拟器
        if (resJson && resJson.isEmulator) {
            // 弹窗提示 + 退出应用
          
            this.showToast("检测到模拟器环境，禁止使用该应用！", 999999);
            
            // 退出应用
            if (cc.sys.os === cc.sys.OS.ANDROID) {
                setTimeout(() => {
                    console.log("forceExit");
                    jsb.reflection.callStaticMethod(
                        "com/cocos/game/utils/DeviceUtils",
                        "forceExit",
                        "(I)V",
                        0
                    );
                }, 500);
            }

            return true;
        }else{
            console.log("不是模拟器");
        }
        return false;
    }

    copyDeviceInfo(){
        const deviceInfo = this.deviceInfoLabel.string;
        console.log("deviceInfo:", deviceInfo);
    
        if (cc.sys.isBrowser) {
            // 浏览器环境
            navigator.clipboard.writeText(deviceInfo).then(() => {
                console.log("复制成功");
            }).catch(err => {
                console.error("复制失败:", err);
            });
        } else if (cc.sys.os === cc.sys.OS.ANDROID) {
            // 原生安卓，通过 Java 接口复制
            jsb.reflection.callStaticMethod(
                "com/cocos/game/utils/DeviceUtils", // 你需要创建的工具类
                "copyText",
                "(Ljava/lang/String;)V",
                deviceInfo
            );
        } else {
            console.warn("当前平台不支持复制");
        }
    }

    // 显示toast
    showToast(msg: string, duration: number = 2){
        this.toast.show(msg, duration);
    }


    // 加载用户广告信息
    loadUserAdInfo(){

        let appid = ENV.SDK.ANDROID.APP_ID;
        if (cc.sys.os === cc.sys.OS.IOS) {           
            appid = ENV.SDK.IOS.APP_ID;
        } else if (cc.sys.os === cc.sys.OS.ANDROID) {
            appid = ENV.SDK.ANDROID.APP_ID;
        }

        UserApi.getUserAdInfo(appid).then((res) => {
            UserModel.getInstance().setAdCount(res.ad_count);
            UserModel.getInstance().setTodayAdCount(res.today_ad_count);
        });
    }


    initGame(){
        // 初始化游戏配置
        console.log("initGame");
        
        this.node.getChildByName("homePage").active = true;
        this.node.getChildByName("gamePage").active = false;
        this.node.getChildByName("layerPage").active = false;
        this.node.getChildByName("profile").active = false;
        this.userBtn.active = true;

        // 移除之前的事件监听器，避免重复注册
        this.userBtn.off(Node.EventType.TOUCH_START);
        this.userBtn.on(Node.EventType.TOUCH_START, this.onUserBtn, this);

        // 修改当前关卡
        GameConfig.CURRENT_LEVEL = 1;
    }

    // 详情页按钮
    onUserBtn(){
        console.log("onUserBtn");
        const profilePage = this.node.getChildByName("profile");
        if(profilePage && !profilePage.active){
            profilePage.active = true;
            profilePage.getComponent(Profile).showCloseBtn();
            this.userBtn.active = false;

            try{
                profilePage.getComponent(Profile).loadUserAdInfo();
          
                if(ENV.NATIVE_OPEN){    
                    // 隐藏首页原生广告
                    TaKuSDK.getInstance().removeNativeAd();

                    console.log("anythink_network 显示个人页面原生，隐藏首页原生")
                    //广告tag 显示个人页面原生
                    const userData = new AdCustomRuleBuilder()
                        .setUserId(this.USER_ID)
                        .setAdScene('personal_center')
                        .build();
                    TaKuSDK.getInstance().initNativeAd(null, PlacementType.PERSONAL_CENTER_NATIVE, userData);
                }

                if(ENV.BANNER_OPEN){
                    // 隐藏首页Banner广告
                    TaKuSDK.getInstance().hideBannerAd();

                    // 显示个人中心Banner广告
                    TaKuSDK.getInstance().showPersonalCenterBannerAd();

                    console.log("anythink_network 显示个人页面Banner，隐藏首页Banner")
                }
            }catch(e){
                console.log("广告操作出错", e);
            }

          
        }
    }

    onStartGame(){
        console.log("onStartGame");

        if (ENV.AD_OPEN) {
            try{
                // 预加载插播广告
                TaKuSDK.getInstance().preloadInterstitialAd();
                // // 隐藏Banner广告
                // TaKuSDK.getInstance().hideBannerAd();

                // 隐藏个人中心Banner广告
                // TaKuSDK.getInstance().hidePersonalCenterBannerAd();
            }catch(e){
                console.log("广告操作出错", e);
            }
        }

        this.node.getChildByName("homePage").active = false;

        this.node.getChildByName("gamePage").active = true;
        this.node.getChildByName("gamePage").getComponent(Game).renderLevel();
    }


    // 关闭详情页
    reStartGame(){
        console.log("reStartGame");
        this.initGame();
        
        if (ENV.AD_OPEN) {
            try{

                if(ENV.NATIVE_OPEN){
                    // 删除个人原生广告
                    TaKuSDK.getInstance().removeNativeAd(PlacementType.PERSONAL_CENTER_NATIVE);
    
                    // 显示首页原生原生
                    TaKuSDK.getInstance().initNativeAd(null, PlacementType.NATIVE);

                    console.log("anythink_network 显示首页原生，隐藏个人页面原生")
                }
    
    
                if(ENV.BANNER_OPEN){
                    // 隐藏个人中心Banner广告
                    TaKuSDK.getInstance().hidePersonalCenterBannerAd();
                    
                    // 显示首页Banner广告
                    TaKuSDK.getInstance().reShowBannerAd();

                    console.log("anythink_network 显示首页Banner，隐藏个人页面Banner")
                }
            }catch(e){
                console.log("广告操作出错", e);
            }
        }
    }

    // 显示层
    onShowLayer(type: "success" | "fail"){
        const layerPage= this.node.getChildByName("layerPage");
        layerPage.active = true;

        if(type == "success"){
            layerPage.getChildByName("layer_fail_bg").active = false;
            layerPage.getChildByName("layer_bg").active = true;
            layerPage.getChildByName("star").active = true;
            layerPage.getChildByName("fail_icon").active = false;

        }else{
            layerPage.getChildByName("layer_fail_bg").active = true;
            layerPage.getChildByName("layer_bg").active = false;
            layerPage.getChildByName("star").active = false;
            layerPage.getChildByName("fail_icon").active = true;
        }
    }

    //关闭层
    onCloseLayer(){
        const layerPage= this.node.getChildByName("layerPage");
        layerPage.active = false;

        // 判断当前关卡是否是最后一关
        if(GameConfig.CURRENT_LEVEL == GameConfig.TOTAL_LEVELS){

            const profile = this.node.getChildByName("profile");
            
            if (ENV.AD_OPEN) {
                // 场景中获取 
                if(ENV.BANNER_OPEN){
                    // 关闭首页Banner广告
                    TaKuSDK.getInstance().hideBannerAd();

                    // 显示个人中心Banner广告   
                    TaKuSDK.getInstance().showPersonalCenterBannerAd();
                }

                if(ENV.NATIVE_OPEN){
                    // 删除首页原生广告
                    TaKuSDK.getInstance().removeNativeAd(PlacementType.NATIVE);
                    // 显示个人中心原生广告
                    TaKuSDK.getInstance().initNativeAd(null, PlacementType.PERSONAL_CENTER_NATIVE);
                }
            }
            profile.active = true;

            profile.getComponent(Profile).loadUserAdInfo();
            profile.getComponent(Profile).hideCloseBtn();






        }else{
            this.node.getChildByName("gamePage").getComponent(Game).nextLevel();
            
            // if (ENV.AD_OPEN && GameConfig.CURRENT_LEVEL == GameConfig.TOTAL_LEVELS - 1) {
            //     // 预加载原生广告
            //     TaKuSDK.getInstance().initNativeAd();
            // }
        }
    }

    // 关闭用户层
    onCloseUserLayer(){
        const profilePage = this.node.getChildByName("profile");
        if(profilePage && profilePage.active){
            profilePage.active = false;
            this.userBtn.active = true;

            if(ENV.NATIVE_OPEN){
                // 删除个人原生广告
                TaKuSDK.getInstance().removeNativeAd(PlacementType.PERSONAL_CENTER_NATIVE);

                // 显示首页原生原生
                TaKuSDK.getInstance().initNativeAd(null, PlacementType.NATIVE);

                console.log("anythink_network 显示首页原生，隐藏个人页面原生")
            }


            if(ENV.BANNER_OPEN){
                // 隐藏个人中心Banner广告
                TaKuSDK.getInstance().hidePersonalCenterBannerAd();

                // 显示首页Banner广告
                TaKuSDK.getInstance().reShowBannerAd();

                console.log("anythink_network 显示首页Banner，隐藏个人页面Banner")
            }
        }
    }
   
}

